package com.whmnx.my.ui.viewmodel;

import android.app.Application;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.whmnx.base.bean.BeanRecordBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.CommonUtil;
import com.whmnx.base.utils.UItils;
import com.whmnx.my.R;
import com.whmnx.my.databinding.FragmentTixianBinding;
import com.whmnx.my.ui.fragment.MyGoTiXianFragment;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * author : huang
 * date   : 2020/9/24 0024 18:23
 * version: 1.0
 */
public class TixianModel extends ToolbarViewModel implements View.OnClickListener {


    public ObservableInt view2Visibility = new ObservableInt(View.GONE);
    public ObservableInt codeVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt loginPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt renloginPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt payPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt renpayPasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt pasVisibility = new ObservableInt(View.VISIBLE);
    public ObservableInt llVisibility = new ObservableInt(View.GONE);
    public ObservableInt llVisibility2 = new ObservableInt(View.VISIBLE);

    public ObservableField<String> ali_Account = new ObservableField<>("");
    public ObservableField<String> ali_Name = new ObservableField<>("");
    public ObservableField<String> idCard = new ObservableField<>("");
    public ObservableField<String> bankCardNum = new ObservableField<>("");
    public ObservableField<String> bankName = new ObservableField<>("");
    public ObservableField<String> bankCard = new ObservableField<>("");
    public ObservableField<String> payeeName = new ObservableField<>("");
    public ObservableField<String> amount = new ObservableField<>("");
    public ObservableField<String> branchName = new ObservableField<>("");
    public ObservableField<String> payeeMoney = new ObservableField<>("");

    private PopupWindow mValidatePayPasswordPopWindow;

    private EditText et_password;

    private String alreadyInputPassword;
    private boolean isFirstInputPassword = true;
    private boolean isCanClear = true;




    public ObservableInt viewVisibility = new ObservableInt(View.VISIBLE);
    MyGoTiXianFragment mFragment;
    FragmentTixianBinding mBinding;
    private int type2;
    private String balance;

    public TixianModel(@NonNull Application application) {
        super(application);
    }

    public void initToolbar(MyGoTiXianFragment myGoTiXianFragment, FragmentTixianBinding binding) {
        this.mFragment = myGoTiXianFragment;
        this.mBinding = binding;
        setTitleText("提现");
        balance = SPUtils.getInstance().getString("balance");
        payeeMoney.set(balance);
    }

    //上方 登录按钮的点击事件
    public BindingCommand llLoginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
             type2 = 0;
            viewVisibility.set(View.VISIBLE);
            view2Visibility.set(View.INVISIBLE);
            llVisibility.set(View.GONE);
            llVisibility2.set(View.VISIBLE);
            mBinding.tv.setTextColor(mFragment.getActivity().getResources().getColor(R.color.appColor));
            mBinding.tv2.setTextColor(mFragment.getActivity().getResources().getColor(R.color.textColor));
          //  textColor.set(R.color.blue);
        }
    });
    //上方 注册按钮的点击事件
    public BindingCommand llRegistOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            type2 = 1;
            view2Visibility.set(View.VISIBLE);
            viewVisibility.set(View.INVISIBLE);
            llVisibility.set(View.VISIBLE);
            llVisibility2.set(View.GONE);
            mBinding.tv.setTextColor(mFragment.getActivity().getResources().getColor(R.color.textColor));
            mBinding.tv2.setTextColor(mFragment.getActivity().getResources().getColor(R.color.appColor));
        }
    });
    //提现
    public BindingCommand ClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (Double.valueOf(amount.get()) > Double.valueOf(balance)){
                ToastUtil.toastShortMessage("提现金额不足");
                return;
            }

            if (type2 == 0){
                if (TextUtils.isEmpty(ali_Account.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(ali_Name.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(idCard.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(amount.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
            }else {
                if (TextUtils.isEmpty(bankName.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(branchName.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(bankCard.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }
                if (TextUtils.isEmpty(payeeName.get())){
                    ToastUtil.toastShortMessage("请输入");
                    return;
                }


            }
            showPossWord();


        }
    });

    private void showPossWord() {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(mFragment.getActivity()).inflate(R.layout.popwindow_validate_pay_password, null);
        et_password = contentView.findViewById(R.id.et_password);
        final TextView tv_pwd_one = contentView.findViewById(R.id.tv_pwd_one);
        final TextView tv_pwd_two = contentView.findViewById(R.id.tv_pwd_two);
        final TextView tv_pwd_three = contentView.findViewById(R.id.tv_pwd_three);
        final TextView tv_pwd_four = contentView.findViewById(R.id.tv_pwd_four);
        final TextView tv_pwd_five = contentView.findViewById(R.id.tv_pwd_five);
        final TextView tv_pwd_six = contentView.findViewById(R.id.tv_pwd_six);
        final ImageView iv_close = contentView.findViewById(R.id.iv_close);
        final TextView tv_forget_password = contentView.findViewById(R.id.tv_forget_password);
        final TextView tv_money = contentView.findViewById(R.id.tv_money);

        tv_pwd_one.setOnClickListener(this);
        tv_pwd_two.setOnClickListener(this);
        tv_pwd_three.setOnClickListener(this);
        tv_pwd_four.setOnClickListener(this);
        tv_pwd_five.setOnClickListener(this);
        tv_pwd_six.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                switch (s.length()) {
                    case 0:
                        if (isCanClear) {
                            tv_pwd_one.setText("");
                        }
                        break;
                    case 1:
                        tv_pwd_one.setText(s.toString().substring(0, 1));
                        tv_pwd_two.setText("");
                        break;
                    case 2:
                        tv_pwd_two.setText(s.toString().substring(1, 2));
                        tv_pwd_three.setText("");
                        break;
                    case 3:
                        tv_pwd_three.setText(s.toString().substring(2, 3));
                        tv_pwd_four.setText("");
                        break;
                    case 4:
                        tv_pwd_four.setText(s.toString().substring(3, 4));
                        tv_pwd_five.setText("");
                        break;
                    case 5:
                        tv_pwd_five.setText(s.toString().substring(4, 5));
                        tv_pwd_six.setText("");
                        break;
                    case 6:
                        if (!isFirstInputPassword) {
                            if (s.toString().equals(alreadyInputPassword)) {
                                //密码通过
                                setPayPwd(alreadyInputPassword);
                            } else {
                               //  ToastUtil.toastShortMessage("交易密码输入错误");
                            }
                        }
                        tv_pwd_six.setText(s.toString().substring(5, 6));
                        if (isFirstInputPassword) {
                            alreadyInputPassword = s.toString();
                            if (s.toString().equals(alreadyInputPassword))
                                setPayPwd(alreadyInputPassword);
                        }

                        //  Utils.showToastSafe("支付密码输入错误");
                        tv_pwd_one.setText("");
                        tv_pwd_two.setText("");
                        tv_pwd_three.setText("");
                        tv_pwd_four.setText("");
                        tv_pwd_five.setText("");
                        tv_pwd_six.setText("");
                        isCanClear = false;
                        et_password.setText("");
                        isCanClear = true;
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (UItils.getDeviceDensity(mFragment.getActivity()).widthPixels / 1.1), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
       // mValidatePayPasswordPopWindow.setFocusable(true);
        //点击外部消失
        mValidatePayPasswordPopWindow.setOutsideTouchable(true);
        mValidatePayPasswordPopWindow.setBackgroundDrawable(new BitmapDrawable());

        //设置获得焦点，否则无法点击
        //   mValidatePayPasswordPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        //   mValidatePayPasswordPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        View rootView = LayoutInflater.from(mFragment.getActivity()).inflate(R.layout.fragment_about, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        //    openKeybord();
        mValidatePayPasswordPopWindow.setOnDismissListener(() -> setBackgroundAlpha(1));
    }

    /**
     * 验证交易密码
     * @param alreadyInputPassword
     */
    private void setPayPwd(String alreadyInputPassword) {
        String pasWord = UItils.md5Digest(alreadyInputPassword);
        if (pasWord.equals(SPUtils.getInstance().getString(Constants.PAYWORD))){
            Map<String, Object> params = new HashMap<>();
            params.put("userInfoId", SPUtils.getInstance().getString(Constants.USERID));
            if (type2 == 0) {
                params.put("payType", 0);
                params.put("type", SPUtils.getInstance().getInt("type"));
                params.put("ali_Account", ali_Account.get());
                params.put("ali_Name", ali_Name.get());
                params.put("idCard", idCard.get());
                params.put("amount", amount.get());
            }else {
                params.put("payType", 1);
                params.put("type", SPUtils.getInstance().getInt("type"));
                params.put("bankName", bankName.get());
                params.put("branchName", branchName.get());
                params.put("bankCardNum", bankCard.get());
                params.put("payeeName", payeeName.get());
                params.put("amount", amount.get());
            }
            HttpClient.post(mFragment.getActivity(), Constants.ADDWITHDRAW, params,new CallBack<BeanRecordBean>() {
                @Override
                public void onSuccess(BeanRecordBean beanRecordBean) {
                    mValidatePayPasswordPopWindow.dismiss();
                    RxBus.getDefault().post(EventConstants.TIXIAN);
                    finish();
                }
            });
        }else {
            ToastUtil.toastShortMessage("交易密码输入错误");
        }
    }


    public BindingCommand ClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            amount.set(payeeMoney.get());
        }
    });


    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = mFragment.getActivity().getWindow().getAttributes();
        lp.alpha = v;
        mFragment.getActivity().getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_pwd_one || id == R.id.tv_pwd_two || id == R.id.tv_pwd_three || id == R.id.tv_pwd_four || id == R.id.tv_pwd_five || id == R.id.tv_pwd_six) {
            CommonUtil.showKeyboard(mFragment.getActivity(), et_password, true);
        } else if (id == R.id.iv_close) {
            mValidatePayPasswordPopWindow.dismiss();
        } else if (id == R.id.tv_forget_password) {
            mValidatePayPasswordPopWindow.dismiss();
        }
    }
}
